/***
 * @Author: XY
 * @Date: 2023-11-09 16:20:14
 * @LastEditors: XY
 * @LastEditTime: 2023-12-14 14:23:30
 * @FilePath: \friendsApp\see_you\src\store\index.js
 **/

import Vue from 'vue'
import Vuex from 'vuex'
import createVuexAlong from 'vuex-along' //vuex-along
import Cookies from "js-cookie";
import siteConfig from "@/store/modules/siteConfig"
import list from '@/store/modules/list'
import axios from "axios";
import { Toast } from 'vant'
import { sy_convertCityNameToCityCode } from '@/utils/location_convert'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: Cookies.get('token'),
    userInfo: { uid: '' },
    app_key: '',
    did: '',
    access_token: '',
    baidu_token: '',
    cityInfo: {}
  },
  getters: {
    cityInfo: state => state.cityInfo,
  },
  mutations: {
    SET_CITYINFO: (state, cityInfo) => {
      state.cityInfo = cityInfo
    },
    SET_USERINFO: (state, userInfo) => {
      console.log(userInfo.uid)
      state.userInfo = { ...userInfo, uid: userInfo.uid }
      Cookies.set("userInfo", JSON.stringify(userInfo))
      // localStorage.setItem("userInfo", JSON.stringify(userInfo))
    },
    SET_TOKEN: (state, token) => {
      state.token = token
      Cookies.set("token", JSON.stringify(token))
      // localStorage.setItem("token", JSON.stringify(token))
    },
    SET_ACCESS_TOKEN: (state, access_token) => {
      state.access_token = access_token
      Cookies.set("access_token", JSON.stringify(access_token))
      // localStorage.setItem("token", JSON.stringify(token))
    },
    SET_BAIDU_TOKEN: (state, baidu_token) => {
      state.baidu_token = baidu_token
      Cookies.set("baidu_token", JSON.stringify(baidu_token))
      // localStorage.setItem("token", JSON.stringify(token))
    },
    SET_APP_KEY: (state, app_key) => {
      state.app_key = app_key;
    },
    SET_DID: (state, did) => {
      state.did = did
    },
  },
  actions: {
    getCityInfo({ commit }) {
      return new Promise((resolve, reject) => {
        AMap.plugin("AMap.Geolocation", () => {
          var geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,
            useNative: true,
            timeout: 10000,
            needAddress: true,
          });
          geolocation.getCurrentPosition((status, result) => {  //获取用户当前的精确位置
            if (status == "complete") {
              if (result.addressComponent) {
                //业务逻辑代码
              } else {
                // commit('SET_CITYINFO', {
                //   lat: result.position.lat,
                //   lng: result.position.lng
                // })

                let key = '8c2e8be40d8b21a1875d08751d0de95e'
                axios.get(`https://restapi.amap.com/v3/geocode/regeo?key=${key}&location=${result.position.lng + ',' + result.position.lat}&extensions=all`)
                  .then((response) => {
                    if (response.data.status) {
                      const results = response.data.regeocode
                      const cityText = sy_convertCityNameToCityCode(
                        results.addressComponent.city && results.addressComponent.city.length > 0
                          ? results.addressComponent.city
                          : results.addressComponent.province,
                          results.addressComponent.adcode
                      )

                      commit('SET_CITYINFO', {
                        lat: result.position.lat,
                        lng: result.position.lng,
                        city_code: cityText[1],
                        city_name: cityText[0]
                      })
                      console.log({
                        lat: result.position.lat,
                        lng: result.position.lng,
                        city_code: cityText[1],
                        city_name: cityText[0]
                      })
                      resolve({
                        lat: result.position.lat,
                        lng: result.position.lng,
                        city_code: cityText[1],
                        city_name: cityText[0]
                      })
                    } else {

                      Toast('未获取定位，请打开定位权限')

                    }
                  })
              }
            }
            else {
              geolocation.getCityInfo((status, result) => {   //只能获取当前用户所在城市和城市的经纬度
                if (status == "complete") {
                  //业务逻辑代码
                } else {
                  that.finishText = '未获取定位'
                }
              })
            }
          })

        })
      })
    }
  },
  modules: { siteConfig, list },
  plugins: [
    createVuexAlong({
      name: "hello-vuex-along", // 设置保存的集合名字，避免同站点下的多项目数据冲突
      local: {
        list: [],
        isFilter: true // 过滤模块 ma 数据， 将其他的存入 localStorage
      },
      session: {
        list: ["app_key"] // 保存 count 和模块 ma 中的 a1 到 sessionStorage
      }
      //如果对于sessionstorage不进行任何操作，也可将session设为false
    })
  ]
})
